'''
@IDE ：PyCharm
@Author ：知了-海龙
@Date ：2021/8/13 15:17
@Email：hallen200806@163.com
@Desc ：user模块数据库操作方法
'''

from sqlalchemy.orm import Session
from models.user.user_model import Docs
from models.user.user_model import User,Shares,ShareItem
from models.permission.permission_model import Permission
import datetime
from utils.get_random import get_random_num,get_timestemp

# 分页
# SELECT * from `user` LIMIT (page-1)*pagesize,5
def get_doc_pagenation(db:Session,page_size:int,current_page:int,pid:int,flag:int,user_id:int) -> [Docs]:
    if flag == 0:
        docs = db.query(
            Docs.id,
            Docs.name,
            Docs.flag,
            Docs.pid,
            Docs.filepath,
            Docs.filetype,
            Docs.create_time
        ).filter(Docs.pid == pid,Docs.user_id==user_id).order_by(Docs.id.desc()).limit(page_size).offset(
            (current_page - 1) * page_size).all()

    elif flag == 1 or flag == 2:
        docs = db.query(
            Docs.id,
            Docs.name,
            Docs.flag,
            Docs.pid,
            Docs.filepath,
            Docs.filetype,
            Docs.create_time
        ).filter(Docs.pid == pid,Docs.flag == flag,Docs.user_id==user_id).order_by(Docs.id.desc()).limit(page_size).offset((current_page-1)*page_size).all()
    else:
        docs = []

    return docs

# 获取总数量
def get_doc_total(db:Session,pid:int,flag:int,user_id:int) -> int:

    if flag == 0:
        total = db.query(Docs).filter(Docs.pid == pid,Docs.user_id==user_id).count()
    elif flag == 1 or flag == 2:
        total = db.query(Docs).filter(Docs.pid == pid,Docs.flag == flag,Docs.user_id==user_id).count()
    else:
        total = 0
    return total


# 文档编辑
def doc_update(db:Session,id:int,name:str):
    role = db.query(Docs).filter(Docs.id == id).first()
    role.name = name
    db.commit()
    db.flush()

# 根据文档id删除文档
def delete_doc_by_id(db:Session,id:int):
    doc = db.query(Docs).filter(Docs.id == id).first()
    db.delete(doc)
    delete_child_doc(db,doc)
    db.commit()
    db.flush()



def delete_share_by_id(db:Session,id:int):
    shares = db.query(Shares).filter(Shares.id == id).all()
    for share in shares:
        db.delete(share)
    db.commit()
    db.flush()

def delete_shareitem_by_shareid(db:Session,id:int):
    del_share_docs = db.query(ShareItem).filter(ShareItem.share_id == id).all()
    for del_share_doc in del_share_docs:
        db.delete(del_share_doc)
    db.commit()
    db.flush()

def get_share_id_by_doc_id(db:Session,doc_id:int):
    share = db.query(ShareItem.share_id).filter(ShareItem.doc_id == doc_id).first()
    if share:
        return share.share_id


def delete_child_doc(db:Session,doc:Docs):
    doc_childs = db.query(Docs).filter(Docs.pid == doc.id).all()
    if doc_childs:
        for doc_child in doc_childs:
            share_id = get_share_id_by_doc_id(db, doc_child.id)
            delete_shareitem_by_shareid(db,share_id)
            delete_share_by_id(db,share_id)
            delete_child_doc(db,doc_child)
    else:
        db.delete(doc)







# 添加文件夹
def add_docs(db:Session,name:str,user_id:int,pid:int,path:str):
    doc = Docs(
        name = name,
        flag = 1,
        pid = pid,
        user_id = user_id,
        filepath = path

    )

    db.add(doc)
    db.commit()
    db.flush()

pname = ""
def get_pname_by_pid(db:Session,pid:int) -> str:
    doc:Docs = db.query(Docs).filter(Docs.id == pid).first()
    # name_list = ["四级文件夹","三级文件夹","二级文件夹","一级文件夹",]
    name = doc.name
    name_list = [name]
    if doc.pid != 0:
        name_list = get_parent_name(db,doc,name_list)
    return name_list

# 递归查找父级name：pname
def get_parent_name(db:Session,doc:Docs,name_list:[str]):
    doc_p:Docs = db.query(Docs).filter(Docs.id == doc.pid).first()
    name_list.append(doc_p.name)
    if doc_p.pid != 0:
        get_parent_name(db,doc_p,name_list)
    return name_list

def get_doc_by_name(db:Session,name:str) -> [Docs]:
    docs = db.query(Docs).filter(Docs.name == name).all()
    return docs

def query_docs(db:Session,q:str,page_size:int,current_page:int,pid:int,flag:int,userid:int) -> [Docs]:
    if flag == 0:
        docs = db.query(
            Docs.id,
            Docs.name,
            Docs.flag,
            Docs.pid,
            Docs.filepath,
            Docs.filetype,
            Docs.create_time
        ).order_by(Docs.id.desc()).filter(Docs.name.like('%' + q + '%'), Docs.pid == pid,Docs.user_id == userid).limit(page_size).offset(
            (current_page - 1) * page_size).all()
    elif flag == 1 or flag == 2:
        docs = db.query(
            Docs.id,
            Docs.name,
            Docs.flag,
            Docs.pid,
            Docs.filepath,
            Docs.filetype,
            Docs.create_time
        ).filter(Docs.name.like('%'+q+'%'),Docs.pid == pid,Docs.flag == flag).limit(page_size).offset((current_page-1)*page_size).all()
    else:
        docs = []
    return docs

def get_docs_query_totle(db:Session,q:str,pid:int,flag:int) -> int:
    if flag == 0:
        total = db.query(Docs).filter(Docs.name.like('%'+q+'%'),Docs.pid == pid).count()
    elif flag == 1 or flag == 2:
        total = db.query(Docs).filter(Docs.name.like('%'+q+'%'),Docs.pid == pid,Docs.flag == flag).count()
    else:
        total = 0
    return total



def save_upload(db:Session,filename:str,pid:int,flag:int,filepath:str,filetype:str,user_id:int,resource_name:str):

    doc = Docs(
        name = filename,
        flag = flag,
        pid = pid,
        filepath = filepath,
        filetype = filetype,
        user_id = user_id,
        resouce_name = resource_name
    )

    db.add(doc)
    db.commit()
    db.flush()

def get_path_by_pid(db:Session,pid:int) -> str:
    doc:Docs = db.query(Docs).filter(Docs.id == pid).first()
    return doc.filepath

def share_db_add(
        db:Session,
        user_id:int,
        share_url:str,
        share_pwd:str,
        share_type:int,
        end_time:datetime.datetime,
        state:int,
        numType:int,
        nums:int,
        doc_id:int
):
    share = Shares(
        user_id = user_id,
        share_url = share_url,
        share_pwd = share_pwd,
        share_type = share_type,
        end_time = end_time,
        state = state,
        numType = numType,
        nums = nums,
    )

    db.add(share)

    db.commit()
    db.flush()

    share_item = ShareItem(
        share_id = share.id,
        doc_id = doc_id
    )
    db.add(share_item)

    db.commit()
    db.flush()


def share_db_adds(
        db:Session,
        user_id:int,
        share_url:str,
        share_pwd:str,
        share_type:int,
        end_time:datetime.datetime,
        state:int,
        numType:int,
        nums:int,
        doc_ids:[str]
):
    share = Shares(
        user_id = user_id,
        share_url = share_url,
        share_pwd = share_pwd,
        share_type = share_type,
        end_time = end_time,
        state = state,
        numType = numType,
        nums = nums,
    )

    db.add(share)

    db.commit()
    db.flush()

    for doc_id in doc_ids:
        share_item = ShareItem(
            share_id = share.id,
            doc_id = doc_id
        )
        db.add(share_item)

    db.commit()
    db.flush()


def share_db_varify(db:Session,share_url:str,share_pwd:str) -> Shares:
    share:Shares = db.query(Shares).filter(Shares.share_url == share_url,Shares.share_pwd == share_pwd).first()

    return share


# 分页
# SELECT * from `user` LIMIT (page-1)*pagesize,5
def get_share_docs_pagenation(db:Session,page_size:int,current_page:int,share_id:int) -> [Docs]:

    share:Shares = db.query(Shares).filter(Shares.id == share_id).first()

    if share.numType == 2 and share.nums <= 0: # 表示有人数限制
        docs = []
    elif share.share_type != 1:  # 表示有过期时间
        now_time = datetime.datetime.now()
        # end_time = "2021-8-29 15:22:33"
        # now_time = "2021-8-30 15:22:33"
        if now_time > share.end_time:  # 当前时间大于endtime表示已过期
            docs = []
        else:
            docs = db.query(ShareItem.doc_id).filter(ShareItem.share_id == share.id).all()

            doc_ids = []
            for doc in docs:
                doc_ids.append(doc.doc_id)

            docs = db.query(
                Docs.id,
                Docs.name,
                Docs.flag,
                Docs.pid,
                Docs.filepath,
                Docs.filetype,
                Docs.create_time
            ).filter(Docs.id.in_(doc_ids)).order_by(Docs.id.desc()).limit(page_size).offset(
                (current_page - 1) * page_size).all()



    else:
        docs = db.query(ShareItem.doc_id).filter(ShareItem.share_id == share.id).all()


        doc_ids = []
        for doc in docs:
            doc_ids.append(doc.doc_id)

        docs = db.query(
            Docs.id,
            Docs.name,
            Docs.flag,
            Docs.pid,
            Docs.filepath,
            Docs.filetype,
            Docs.create_time
        ).filter(Docs.id.in_(doc_ids)).order_by(Docs.id.desc()).limit(page_size).offset((current_page-1)*page_size).all()


    if share.numType == 2:
        if share.nums > 0:
            share.nums = share.nums - 1
            db.commit()
            db.flush()
            db.refresh(share)
    return docs

def get_doc_by_id(db:Session,doc_id:int) -> Docs:
    doc = db.query(Docs).filter(Docs.id == doc_id).first()
    return doc

def get_docs_by_ids(db:Session,ids:[str]):

    docs = db.query(Docs).filter(Docs.id.in_(ids)).all()
    name = ""
    path = ""
    for doc in docs:
        if doc.pid != 0:
            doc = db.query(Docs).filter(Docs.id == doc.pid).first()
            name = doc.name
            path = doc.filepath
        else:
            name = get_random_num(12) + "-" + get_timestemp()
            path = "uploads/docs/"

    return (docs,name,path)


